﻿/*
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
 *
 * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

#include <map>
#include <iostream>
#include "Util/MD5.h"
#include "Util/File.h"
#include "Util/logger.h"
#include "Util/SSLBox.h"
#include "Util/util.h"
#include "Network/TcpServer.h"
#include "Common/config.h"
#include "Rtsp/RtspSession.h"
#include "Rtmp/RtmpSession.h"
#include "Http/HttpSession.h"
#include "Rtp/RtpSelector.h"

using namespace std;
using namespace toolkit;
using namespace mediakit;


std::map<uint16_t,uint16_t, std::less<uint16_t> > check_rangs{
    {42871 , 42878},
    {43065 , 43068},
};

bool CheckInRange(const uint16_t seq) {
    for(auto it = check_rangs.begin(); it != check_rangs.end();it++) {
        if(seq >= it->first && seq <= it->second) {
            return true;
        }
    }
    return false;
}
#if defined(ENABLE_RTPPROXY)
#define DEBUG_RTP_READ

static bool loadFile(const char *path){
    FILE *fp = fopen(path, "rb");
    if (!fp) {
        WarnL << "open file failed:" << path;
        return false;
    }

    uint32_t timeStamp_last = 0;
    uint16_t len;
    char rtp[2 * 1024];
    struct sockaddr addr = {0};
    auto sock = Socket::createSocket();
    size_t total_size = 0;
    while (true) {
        if (2 != fread(&len, 1, 2, fp)) {
            WarnL;
            break;
        }
        len = ntohs(len);
        if (len < 12 || len > sizeof(rtp)) {
            WarnL << len;
            break;
        }
        #ifdef DEBUG_RTP_READ
//         else{
//             printf("读取长度为%u的rtp包,0X%x,0x%X\n",len,(len&0xff00)>>8,len&0x00ff);
//         }
        #endif
        if (len != fread(rtp, 1, len, fp)) {
            WarnL;
            break;
        }
        #ifdef DEBUG_RTP_READ
        else{
            #if 1
            RtpHeader *header = (RtpHeader *) rtp;
            printf("rtp包序号:%u,pt:%u\n",header->seq,header->pt);
            #else
            uint16_t rtp_seq = rtp[2];
            rtp_seq <<= 8;
            rtp_seq |= rtp[3];
            if(CheckInRange(rtp_seq)) {
                printf("rtp包序号:%u\n",rtp_seq);
            }
            #endif
        }
        #endif
        total_size += len;
        uint32_t timeStamp;

        RtpSelector::Instance().async_inputRtp(sock, rtp, len, &addr, &timeStamp);
        auto diff = timeStamp - timeStamp_last;
        if (diff > 0 && diff < 500) {
            usleep(diff * 1000);
        } else {
            usleep(1 * 1000);
        }
        timeStamp_last = timeStamp;
    }
    WarnL << total_size / 1024 << "KB";
    fclose(fp);
    return true;
}
#endif//#if defined(ENABLE_RTPPROXY)
/**
 /opt/record/stream_34020000001320000001_34020000001310000001_0200000001.rtp
 */
int main(int argc,char *argv[]) {
    //设置日志
    Logger::Instance().add(std::make_shared<ConsoleChannel>("ConsoleChannel"));
#if defined(ENABLE_RTPPROXY)
    //启动异步日志线程
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
    loadIniConfig((exeDir() + "config.ini").data());
    TcpServer::Ptr rtspSrv(new TcpServer());
    TcpServer::Ptr rtmpSrv(new TcpServer());
    TcpServer::Ptr httpSrv(new TcpServer());
    rtspSrv->start<RtspSession>(5554);//默认554
    rtmpSrv->start<RtmpSession>(19351);//默认1935
    httpSrv->start<HttpSession>(81);//默认80
    //此处选择是否导出调试文件
//    mINI::Instance()[RtpProxy::kDumpDir] = "/Users/xzl/Desktop/";
#if 0
    EventPoller::Ptr m_poller = EventPollerPool::Instance().getPoller();
    Timer::Ptr m_send_pkt_timer = std::make_shared<Timer>(5,[&](){
        MediaSource::for_each_media([&](const MediaSource::Ptr &media){
            std::cout << "schema:" << media->getSchema() << ",vhost:" << media->getVhost() << ",app:" << media->getApp() << ",Id:" << media->getId() << std::endl;
            });
        return true;
    }, m_poller);
#endif
    if (argc == 2)
      loadFile(argv[1]);
    else
      ErrorL << "parameter error.";
#else
    ErrorL << "please ENABLE_RTPPROXY and then test";
#endif//#if defined(ENABLE_RTPPROXY)
    return 0;
}


